package com.efuture.servlet.session.logindemo.service;
import com.efuture.servlet.session.logindemo.dao.UserDao;
import com.efuture.servlet.session.logindemo.domain.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;


@WebServlet("/YzmLoginServlet")
public class YzmLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//         用户输入用户名，密码以及验证码。
//		   如果用户名和密码输入有误，跳转登录页面，提示:用户名或密码错误
//         如果验证码输入有误，跳转登录页面，提示：验证码错误
//         如果全部输入正确，则跳转到主页success.jsp，显示：用户名,欢迎您

        response.setCharacterEncoding("utf-8");
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        session.removeAttribute("checkCode_session");
        if(null==checkCode_session||!checkCode_session.equalsIgnoreCase(checkCode)){
            //验证码输入错误 转发到登录界面
            request.setAttribute("cc_error","验证码错误");
            request.getRequestDispatcher("/yzmlogin.jsp").forward(request,response);
            return;
        }
        if(null==userName||userName.length()<1||null==passWord||passWord.length()<1){
            request.setAttribute("login_error","用户名或者密码错误");
            request.getRequestDispatcher("/yzmlogin.jsp").forward(request,response);;
            return;
        }
        User loginUser = new User();
        loginUser.setUserName(userName);
        loginUser.setPassWord(passWord);
        UserDao userDao = new UserDao();
        User user = userDao.login(loginUser);
        if(null!=user){
            //重定向到登录成功页面
            session.setAttribute("user",user.getUserName());
            System.out.println("request.getContextPath():"+request.getContextPath());
            if(null!=request.getContextPath()&&request.getContextPath().length()>0){
                response.sendRedirect(request.getContextPath()+"/yzmloginsuccess.jsp");
            }else{
                response.sendRedirect("/yzmloginsuccess.jsp");
            }
            return;
        }else{
            //用户名密码错误 转发到登录界面
            request.setAttribute("login_error","用户名或者密码错误");
            request.getRequestDispatcher("/yzmlogin.jsp").forward(request,response);;
            return;
        }
    }
}
